import { Injectable } from '@angular/core';
import { Subject } from "rxjs/Subject";

export interface LoadingParams {
  id: string;
  toShow: boolean;
}

/**
 * Loading服务的驱动端；需要执行Loading操作的源引入本服务；
 * 
 * @export
 * @class LoadingService
 */
@Injectable()
export class LoadingService {
  loadingObs: Subject<LoadingParams> = new Subject();
  inLoading = {};

  constructor() { }
  
  
  /**
   * 驱动Loading展示
   * 
   * @param {any} [id=undefined] 
   * 相应的目标Loading组件；
   * 默认值为undefined，
   * 此时进行匿名广播，接收匿名广播以及全局广播的Loading进行响应；
   * 如指定id,则接收该id的广播及全局广播的Loading进行响应
   * 
   * @memberOf LoadingService
   */
  showLoading(id = undefined) {
    // console.debug("IN LOADING: ", JSON.stringify(this.inLoading));
    this.inLoading[id] = id in this.inLoading ? this.inLoading[id] + 1 : 1;
    this.loadingObs.next({
      id,
      toShow: true
    });
  }

  /**
   * 驱动Loading隐藏
   * 同showLoading
   * 
   * @param {any} [id=undefined]
   * 
   * @memberOf LoadingService
   */
  hideLoading(id = undefined) {
    this.inLoading[id] -= 1;
    this.loadingObs.next({
      id,
      toShow: false
    });
  }
}